import { createStore, createLogger } from "vuex";
import { login } from "@/api";
import axios from "axios";
export interface RootState {
  userInfo: any;
  questions: {
    type: string;
    id: string;
    list: {
      title: string;
      anwer: ["是", "不确定", "不是"];
      id: string;
    }[];
  }[];
}
export default createStore<RootState>({
  state: {
    userInfo: {
      isLogin: false,
      username: "",
      nickname: "",
      avator: "",
      token: "",
    },
    questions: [],
  },
  getters: {},
  mutations: {
    loginSuccess(state, payload) {
      state.userInfo = payload;
    },
    loginError(state, payload) {
      state.userInfo = {
        isLogin: false,
        username: "",
        nickname: "",
        avator: "",
        token: "",
      };
    },
    setQuestions(state, payload) {
      state.questions = payload;
    },
  },
  actions: {
    async login(context, payload: { username: string; password: string }) {
      try {
        const resp = await login(payload);
        const { code, message, data } = resp.data;
        if (code === 200) {
          context.commit("loginSuccess", {
            isLogin: true,
            ...data,
          });
        } else {
          context.commit("loginError");
        }
        return resp;
      } catch (e: any) {
        context.commit("loginError");
        return e.message;
      }
    },
    async fetchQuestion(context) {
      const resp = await axios.get("/questions");
      context.commit("setQuestions", resp.data.data);
    },
  },
  modules: {},
  plugins: [createLogger()],
});
